package com.primal.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * Author whh
 * Date 2023/11/01/ 18:45
 * <p></p>
 */
public class XMLPathUtil {
    static String EXAMPLE_STRING = "<?xml version=\"1.0\"?>" +
            "<Tutorials>\n" +
            "    <Tutorial tutId=\"01\" type=\"java\">\n" +
            "        <title>Guava</title>\n" +
            "  <description>Introduction to Guava</description>\n" +
            "  <date>04/04/2016</date>\n" +
            "  <author>GuavaAuthor</author>\n" +
            "    </Tutorial>\n" +
            "    <Tutorial tutId=\"02\" type=\"java\">\n" +
            "        <title>XML</title>\n" +
            "  <description>Introduction to XPath</description>\n" +
            "  <date>04/05/2016</date>\n" +
            "  <author>XMLAuthor</author>\n" +
            "    </Tutorial>\n" +
            "</Tutorials>";

    public static void main(String[] args) throws Exception {



        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(new ByteArrayInputStream(EXAMPLE_STRING.getBytes()));
        XPath xPath = XPathFactory.newInstance().newXPath();
        String expression1 = "/Tutorials/Tutorial";
        NodeList nodeList = (NodeList) xPath.compile(expression1).evaluate(xmlDocument, XPathConstants.NODESET);

        System.out.println("Find nodes length = " + nodeList.getLength());


        String expression2 = "/Tutorials/Tutorial[@tutId=\"01\"]";
        Node node = (Node) xPath.compile(expression2).evaluate(xmlDocument, XPathConstants.NODE);
        NodeList childNodes = node.getChildNodes();

        System.out.println("Find node" + node);
    }
}
